package uebung03;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class Integration
{
  private static ExecutorService pool = Executors.newFixedThreadPool(5);
  
  public static double f(double x)
  {
    return 2*x;
  }
  
  class Ai implements Callable<Double>
  {
    private int i;
    private double h;
    private double a;
    
    public Ai(int i, double h, double a)
    {
      this.i = i;
      this.h = h;
      this.a = a;
    }
    
    @Override
    public Double call() throws Exception {
      return f(a+i*h)*h;
    }
  }
  
  @SuppressWarnings("unchecked")
  public static void main(String[] args)
  { 
    Integration integration = new Integration();
    
    int n = 100;
    double a = 0;
    double b = 5;
    double h = (b-a)/n;
    
    Future<Double>[] futures = new Future[n];
    for(int i = 0; i<n; i++)
    {
      Callable<Double> ai = integration.new Ai(i, h, a);
      futures[i] = pool.submit(ai);
    }
    
    double approxIntegral = 0;
    for(int i = 0; i<n; i++)
    {
      try {
        approxIntegral += futures[i].get();
      } catch (InterruptedException e) {
        e.printStackTrace();
      } catch (ExecutionException e) {
        e.printStackTrace();
      }
    }
    System.out.println("Ergebnis: "+approxIntegral);
  }
}
